<?php
/*********************************************
  CPG Dragonfly™ CMS
  ********************************************
  Copyright © 2004 - 2005 by CPG-Nuke Dev Team
  http://www.dragonflycms.com

  Dragonfly is released under the terms and conditions
  of the GNU GPL version 2 or any later version
**********************************************/
if (!defined('ADMIN_PAGES')) { exit; }
if (!can_admin('news')) { die('Access Denied'); }
Dragonfly::getKernel()->L10N->load('News');
require_once('includes/nbbcode.php');
require_once('modules/News/admin/functions.inc');
$mode = isset($_POST['mode']) ? $_POST['mode'] : '';

function themepreview($title, $hometext, $bodytext='', $notes='')
{
	$hometext = BBCode::decodeAll($hometext, 1, true);
	$bodytext = BBCode::decodeAll($bodytext, 1, true);
	echo "<b>$title</b><br /><br />$hometext<br /><br />$bodytext";
	if ($notes != '') { echo '<b>'._NOTE."</b> <i>$notes</i>"; }
}

function puthome($ihome, $acomm)
{
	echo '<br /><b>'._PUBLISHINHOME.'</b>&nbsp;&nbsp;'.yesno_option('ihome', $ihome).'&nbsp;&nbsp;<br />'
		.'<br /><b>'._ACTIVATECOMMENTS.'</b>&nbsp;&nbsp;'.yesno_option('acomm', $acomm).'<br /><br />';
}

function newsorder($display_order)
{
	return '<br /><b>'._DISPLAY_ORDER.' '.select_box('display_order', $display_order, array(0=>_NORMAL, 1=>1, 2=>2, 3=>3, 4=>4, 5=>5, 6=>6, 7=>7, 8=>8, 9=>9, 10=>_TOP_MOST)).'</b><br /><br />';
}

function shownews_edit($hometext, $bodytext)
{
	$story_bbtable = BBCode::getTable('hometext', 'postnews', 1);
	$storyext_bbtable = BBCode::getTable('bodytext', 'postnews', 1);
	echo '<br /><br /><b>'._STORYTEXT.'</b><br />'.$story_bbtable.'
	<textarea wrap="virtual" cols="80" rows="15" name="hometext" onselect="storeCaret(this);" onclick="storeCaret(this);" onkeyup="storeCaret(this);" onchange="storeCaret(this);">'.htmlprepare($hometext).'</textarea><br /><br />
	<b>'._EXTENDEDTEXT.'</b><br />'.$storyext_bbtable.'
	<textarea wrap="virtual" cols="80" rows="25" name="bodytext" onselect="storeCaret(this);" onclick="storeCaret(this);" onkeyup="storeCaret(this);" onchange="storeCaret(this);">'.htmlprepare($bodytext).'</textarea><br />';
}

function autonews_edit($xday, $xmonth, $xyear, $xhour, $xmin)
{
	echo '<br/><input type="datetime-local"><br/><br/>';
	return;
	$today = getdate(time());
	if ($today['mday'] < 10) { $today['mday'] = "0$today[mday]"; }
	if ($today['hours'] < 10) { $today['hours'] = "0$today[hours]"; }
	if ($today['minutes'] < 10) { $today['minutes'] = "0$today[minutes]"; }
	echo '<br /><br />'._NOWIS.": $today[month] $today[mday], $today[year] @ $today[hours]:$today[minutes]:00 GMT<br /><br />"._DAY.': <select name="day">';
	for($i = 1; $i <= 31; $i++) {
		echo '<option'.(($i==$xday)?' selected="selected"':'').'>'.$i.'</option>';
	}
	echo '</select> '._UMONTH.': <select name="month">';
	for ($i = 1; $i <= 12; $i++) {
		echo '<option'.(($i==$xmonth)?' selected="selected"':'').'>'.$i.'</option>';
	}
	echo '</select> '._YEAR.': <select name="year">';
	for ($i = $today['year']; $i <= $today['year']+3; $i++) {
		echo '<option'.(($i==$xyear)?' selected="selected"':'').'>'.$i.'</option>';
	}
	echo '</select><br />'._HOUR.': <select name="hour">';
	for ($i = 0; $i <= 23; $i++) {
		$dummy = ($i < 10) ? "0$i" : $i;
		echo '<option'.(($i==$xhour)?' selected="selected"':'').'>'.$dummy.'</option>';
	}
	echo '</select> : <select name="min">';
	$i = 0;
	while ($i <= 59) {
		$dummy = ($i < 10) ? "0$i" : $i;
		echo '<option'.(($i==$xmin)?' selected="selected"':'').'>'.$dummy.'</option>';
		$i += 5;
	}
	echo '</select> : 00 GMT<br /><br />';
}

function SelectCategory($cat=0)
{
	global $prefix, $db;
    $selcat = $db->sql_query("SELECT catid, title FROM {$prefix}_stories_cat
		ORDER BY title");
    echo '<b>'._CATEGORY.'</b> <select name="catid">';
    $sel[$cat] = ' selected="selected"';
    echo "<option value=\"0\" $sel[0]>"._ARTICLES.'</option>';
    while(list($catid, $title) = $db->sql_fetchrow($selcat)) {
        echo "<option value=\"$catid\"".$sel[$catid].">$title</option>";
    }
	echo '</select> [ <a href="'.URL::admin('&amp;mode=catadd').'">'._ADD.'</a> |
		<a href="'.URL::admin('&amp;mode=catedit').'">'._EDIT.'</a> |
		<a href="'.URL::admin('&amp;mode=catdel').'">'._DELETE.'</a> ]';
}

if (isset($_GET['view'])) {
	show_head(_SUBMISSIONSADMIN);
	$result = $db->sql_query('SELECT qid, uid, uname, subject, story, storyext, topic, alanguage FROM '.$prefix."_queue
		WHERE qid=".intval($_GET['view']));
	list($qid, $uid, $uname, $subject, $story, $storyext, $topic, $alanguage) = $db->sql_fetchrow($result);
	story_form($qid, $subject, $story, $storyext, $topic, $uid, $uname, $alanguage);
} else if (isset($_GET['del']) || $mode == 'delete') {
	if ($_GET['del'] == 'all') {
		$db->sql_query('DELETE FROM '.$prefix.'_queue');
		URL::redirect(URL::admin());
	} else {
		$qid = ($mode == 'delete') ? $_POST['qid'] : $_GET['del'];
		$db->sql_query('DELETE FROM '.$prefix.'_queue
			WHERE qid='.intval($qid));
		URL::redirect(URL::admin('News&file=submissions'));
	}
} else if ($mode == 'preview') {
	show_head();
	story_form(intval($_POST['qid']), $_POST['subject'], $_POST['hometext'], $_POST['bodytext'], intval($_POST['topic']), intval($_POST['uid']), $_POST['author'], $_POST['alanguage']);
} else if ($mode == 'post') {
	postStory(intval($_POST['uid']), $_POST['bodytext'], intval($_POST['topic']), $_POST['notes']);
} else {
	show_head(_SUBMISSIONSADMIN);
	$result = $db->sql_query("SELECT qid, subject, timestamp, alanguage FROM ".$prefix."_queue
		ORDER BY timestamp DESC");
	if ($db->sql_numrows($result) < 1) {
		echo sprintf(_ERROR_NONE_TO_DISPLAY,strtolower(_NEWSUBMISSIONS));
	} else {
		echo '<table width="100%">';
		while (list($qid, $subject, $timestamp, $alanguage) = $db->sql_fetchrow($result)) {
			$timestamp = Dragonfly::getKernel()->L10N->date('m-d-Y', $timestamp);
			if ($subject == '') { $subject = _NOSUBJECT; }
			if ($alanguage == '') { $alanguage = _ALL; }
			echo '<tr>
			<td align="center">(<a href="'.URL::admin("News&amp;file=submissions&amp;del=$qid").'">'._DELETE.'</a>)&nbsp;</td>
			<td width="100%"><a href="'.URL::admin("News&amp;file=submissions&amp;view=$qid").'">'.$subject.'</a></td>
			<td align="center">'.$alanguage.'</td>
			<td align="right">'.$timestamp.'</td>
			</tr>';
		}
		echo '</table>';
	}
	if ($db->sql_numrows($result) >= 1) {
		echo '<br /><center>[ <a href="'.URL::admin('News&amp;file=submissions&amp;del=all').'">'._DELETE.' '._ALL.'</a> ]</center>';
	}
	CloseTable();
}

function story_form($qid, $subject, $hometext, $bodytext, $topic, $uid, $author, $alanguage)
{
	global $prefix, $user_prefix, $db, $MAIN_CFG;

	$notes = isset($_POST['notes']) ? $_POST['notes'] : '';

	$subject = htmlprepare($subject);
	echo '<form action="'.URL::admin('News&amp;file=submissions').'" name="postnews" method="post" enctype="multipart/form-data"><b>'._NAME.'</b><br />';
	if ($uid > 1) {
		$res = $db->sql_query("SELECT user_email FROM ".$user_prefix."_users
			WHERE user_id='$uid'");
		list($email) = $db->sql_fetchrow($res);
		echo '<input type="hidden" name="author" value="'.htmlprepare($author).'" />'.htmlprepare($author)
			."&nbsp;&nbsp;[ <a href=\"mailto:$email?subject=Re: $subject\">"._EMAILUSER."</a> | <a href=\"".URL::index("Your_Account&amp;profile=$uid")."\">"._USERPROFILE."</a> | <a href=\"".URL::index("Private_Messages&amp;mode=post&amp;u=$uid")."\">"._SENDPM."</a> ]";
	} else {
		echo '<input type="text" name="author" size="25" value="'.htmlprepare($author).'" />';
	}
	echo "<br /><br /><b>"._TITLE."</b><br /><input type=\"text\" name=\"subject\" size=\"50\" value=\"$subject\" /><br /><br />";
	if ($topic < 1) {
		$topicimage = 'AllTopics.gif';
		$warning = '<strong style="color:red;background:white">'._SELECTTOPIC.'</strong> ';
	} else {
		$result = $db->sql_query("SELECT topicimage FROM ".$prefix."_topics
			WHERE topicid='$topic'");
		list($topicimage) = $db->sql_fetchrow($result);
		$warning = _TOPIC;
	}
	echo "<table width=\"70%\" cellpadding=\"0\" cellspacing=\"1\" border=\"0\" align=\"center\"><tr><td>
	<table width=\"100%\" cellpadding=\"8\" cellspacing=\"1\" border=\"0\"><tr><td>
	<img src=\"images/topics/$topicimage\" border=\"0\" align=\"right\" alt=\""._TOPIC."\" title=\""._TOPIC."\" />";
	themepreview($subject, $hometext, $bodytext, $notes);
	echo "</td></tr></table></td></tr></table>
	<br /><b>$warning</b><select name=\"topic\">";
	$toplist = $db->sql_query("SELECT topicid, topictext FROM ".$prefix."_topics ORDER BY topictext");
	echo "<option value=\"\">"._ALLTOPICS."</option>\n";
	while (list($topicid, $topics) = $db->sql_fetchrow($toplist)) {
		$sel = ($topicid == $topic) ? $sel = ' selected="selected"' : '';
		echo "<option value=\"$topicid\"$sel>$topics</option>\n";
	}
	echo '</select>';
	echo '<br /><br />';
	echo "<table border='0' width='100%' cellspacing='0'><tr><td width='20%'><b>"._ASSOTOPIC."</b></td><td width='100%'>"
		."<table border='0' cellspacing='3' cellpadding='8'><tr>";
	$result = $db->sql_query("SELECT topicid, topictext FROM ".$prefix."_topics
		ORDER BY topictext");
	$a = 0;
	while (list($topicid, $topictext) = $db->sql_fetchrow($result)) {
		$checked = '';
		if ($a == 3) {
			echo '</tr><tr>';
			$a = 0;
		}
		$assotop = isset($_POST['assotop'])?$_POST['assotop']:array();
		for ($i=0; $i<sizeof($assotop); $i++) {
			if ($assotop[$i] == $topicid) {
				$checked = 'checked="checked"';
				break;
			}
		}
		echo "<td><input type='checkbox' name='assotop[]' value='$topicid' $checked />$topictext</td>";
		$a++;
	}
	echo '</tr></table></td></tr></table><br /><br />';
	SelectCategory(isset($_POST['catid']) ? intval($_POST['catid']) : 0);
	echo '<br />';
	puthome((isset($_POST['ihome'])?intval($_POST['ihome']):1), (isset($_POST['acomm'])?intval($_POST['acomm']):1));
	echo newsorder(isset($_POST['display_order']) ? intval($_POST['display_order']) : 0);
	if (Dragonfly::getKernel()->L10N->multilingual) {
		echo '<br /><b>'._LANGUAGE.': </b>'.lang_selectbox(isset($_POST['alanguage'])?$_POST['alanguage']:$alanguage);
	} else {
		echo '<input type="hidden" name="alanguage" value="" />';
	}
	shownews_edit($hometext, $bodytext);
	echo "<span>"._ARESUREURL."</span><br /><br />"
	."<b>"._NOTES."</b><br />"
	."<textarea wrap=\"virtual\" cols=\"50\" rows=\"4\" name=\"notes\">$notes</textarea><br /><br />"
	."<input type=\"hidden\" name=\"qid\" size=\"50\" value=\"".$qid."\" />"
	."<input type=\"hidden\" name=\"uid\" size=\"50\" value=\"$uid\" />";
	echo '<b>'._PROGRAMSTORY.'</b>&nbsp;&nbsp;'.yesno_option('automated', (isset($_POST['automated'])?$_POST['automated']:0));
	if (isset($_POST['day'])) {
		autonews_edit($_POST['day'], $_POST['month'], $_POST['year'], $_POST['hour'], $_POST['min']);
	} else {
		$today = getdate();
		autonews_edit($today['mday'], $today['mon'], $today['year'], $today['hours'], $today['minutes']);
	}
	echo '
<select name="mode">
	<option value="delete">'._DELETESTORY.'</option>
	<option value="preview" selected="selected">'._PREVIEWSTORY.'</option>
	<option value="post">'._POSTSTORY.'</option>
</select> &nbsp; <input type="submit" value="'._GO.'" />';
	CloseTable();
	putpoll((isset($_POST['poll_title'])?$_POST['poll_title']:''), (isset($_POST['option_text'])?$_POST['option_text']:array()));
	echo '</form>';
}

function postStory($uid, $bodytext, $topic, $notes)
{
	global $aid, $prefix, $db, $user_prefix;
	$associated = '';
	if (!empty($_POST['assotop']) && is_array($_POST['assotop'])) {
		$associated = implode(',', preg_grep('#(\d+)#', $_POST['assotop']));
	}
	$subject = Fix_Quotes($_POST['subject'], 1);
	$hometext = Fix_Quotes($_POST['hometext']);
	$bodytext = Fix_Quotes($bodytext);
	$notes = Fix_Quotes($notes);
	$catid = intval($_POST['catid']);
	$ihome = intval($_POST['ihome']);
	$acomm = intval($_POST['acomm']);
	$alanguage = Fix_Quotes($_POST['alanguage']);
	$author = ($uid < 2) ? '' : Fix_Quotes($_POST['author']);
	if ($_POST['automated']) {
		$date = mktime($_POST['hour'], $_POST['min'], 0, $_POST['month'], $_POST['day'], $_POST['year']);
		if ($hometext == $bodytext) $bodytext = '';
		$result = $db->sql_query("INSERT INTO {$prefix}_autonews
			(catid, aid, title, time, hometext, bodytext, topic, informant, notes, ihome, alanguage, acomm, associated)
			VALUES
			('$catid', '$aid', '$subject', '$date', '$hometext', '$bodytext', '$topic', '$author', '$notes', '$ihome', '$alanguage', '$acomm', '$associated')");
		if ($uid > 1) {
			$db->sql_query('UPDATE '.$user_prefix."_users
				SET counter=counter+1
				WHERE user_id='$uid'");
		}
		$db->sql_query('UPDATE '.$prefix."_admins
			SET counter=counter+1
			WHERE aid='$aid'");
		$db->sql_query('DELETE FROM '.$prefix."_queue
			WHERE qid=".intval($_POST['qid']));
		URL::redirect(URL::admin('News&file=submissions'));
	}
	if ($hometext == $bodytext) $bodytext = '';
	$id = 0;
	$poll_title = isset($_POST['poll_title']) ? $_POST['poll_title'] : '';
	$option_text = isset($_POST['option_text']) ? $_POST['option_text'] : '';
	if (!empty($poll_title) && !empty($option_text[1]) && !empty($option_text[2])) {
		$id = $db->TBL->poll_desc->insert(array(
			'poll_title'=>$poll_title,
			'time_stamp'=>time(),
			'planguage'=>$alanguage,
			'comments'=>$acomm
		), 'poll_id');
		for($i = 1; $i <= sizeof($option_text); $i++) {
			$db->TBL->poll_data->insert(array('poll_id'=>$id, 'option_text'=>$option_text[$i], 'vote_id'=>$i));
		}
	}
	$db->sql_query("INSERT INTO {$db->TBL->stories}
		(catid, aid, title, time, hometext, bodytext, comments, counter, topic, informant, notes, ihome, alanguage, acomm, poll_id, score, ratings, associated, display_order)
		VALUES
		('$catid', '$aid', '$subject', ".time().", '$hometext', '$bodytext', '0', '0', '$topic', '$author', '$notes', '$ihome', '$alanguage', '$acomm', '$id', '0', '0', '$associated', ".intval($_POST['display_order']).")");
	$artid = $db->sql_nextid('sid');
	$db->sql_update($prefix.'_poll_desc', array('artid'=>$artid), "poll_id='$id'");
//	  $db->sql_query('UPDATE '.$prefix."_poll_desc SET artid='$artid' WHERE poll_id='$id'");
	if ($uid > 1) {
		$db->sql_query('UPDATE '.$user_prefix."_users
			SET counter=counter+1
			WHERE user_id='$uid'");
	}
	$db->sql_query('UPDATE '.$prefix."_admins
		SET counter=counter+1
		WHERE aid='$aid'");
	$db->sql_query('DELETE FROM '.$prefix.'_queue
		WHERE qid='.intval($_POST['qid']));
	URL::redirect(URL::admin('News&file=submissions'));
}
